<?php

namespace App\Http\Controllers\Home\Wechat;

use Illuminate\Http\Request;

use App\Http\Requests;
//use App\Http\Controllers\Controller;
use App\Models\wechat\Carts;

class CartController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        view()->share([
            '_cart' => 'on'
        ]);
    }

    //显示购物车首页
    public function index()
    {
        $carts=Carts::with('product')->where('customer_id',$this->customer->id)->get();
//        return $carts;
        return view('home.wechat.carts.index')->with('carts',$carts)->with('count',Carts::count_carts($carts));
    }

    //ajax实现购物车商品数量增减
    public function change_num(Request $request)
    {

        if ($request->type == 'add') {
            Carts::where('id', $request->id)->increment('num');
        } else {
            Carts::where('id', $request->id)->decrement('num');
        }
        return Carts::count_carts();

    }

    //ajax实现删除购物车中的商品
    public function delete_cart(Request $request)
    {
        $cart_id=$request->cart_id;
        Carts::destroy($cart_id);
        return Carts::count_carts();
    }

    //在商品show页面 点击'立即购买' 用ajax传递到product_id 到 store方法进行存储，然后跳转到购物车首页/wechat/carts/index
    public function store(Request $request)
    {
        $product_id= $request->product_id;
//        return $product_id;
        $cart=Carts::where('product_id',$product_id)->where('customer_id',$this->customer->id)->first();

        //如果不为空  说明原来购物车有此商品
        if($cart){
            Carts::where('id',$cart->id)->increment('num');
            return; //后面不执行 直接返回
        }

        //否则 购物车表 创建新数据
        Carts::create([
            'product_id' => $request->product_id,
//            'customer_id' => $this->customer->id,
            'customer_id' => $this->customer->id,
        ]);


    }
    
}
